import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/pages/home/index.dart';
import 'package:flutter_enjoy_plus/pages/mine/index.dart';
import 'package:flutter_enjoy_plus/utils/Emitter.dart';
import 'package:flutter_enjoy_plus/utils/TokenManager.dart';

class TabsPage extends StatefulWidget {
  const TabsPage({super.key});

  @override
  _TabsPageState createState() => _TabsPageState();
}

class _TabsPageState extends State<TabsPage> {

  List tabBarList = [
    {
      'label': '首页',
      'icon': 'assets/tabs/home_default.png',
      'activeIcon': 'assets/tabs/home_active.png'
    },
    {
      'label': '我的',
      'icon': 'assets/tabs/my_default.png',
      'activeIcon': 'assets/tabs/my_active.png'
    },
  ];

  int _currentIndex = 0;

  // 父组件定义回调函数
  void updateIndex(int index){
    setState(() {
      _currentIndex = index;
    });
  }

  // 第一种方案 -> 通过index来判断显示哪个页面
  // getTabbarContent(){
  //   if(_currentIndex == 0){
  //     return const HomePage();
  //   }else if(_currentIndex == 1){
  //     return MinePage(currentIndex:_currentIndex,updateIndex:updateIndex);
  //   }
  // }
  // 第二种方案 -> （性能更优）IndexStacked -> 通过index 指定渲染（不会每次都销毁）


  // 获取底部导航栏的item
  List<BottomNavigationBarItem> getBottomNavigationBarItems(){
    List<BottomNavigationBarItem> list = [];
    for(var item in tabBarList){
      list.add(
        BottomNavigationBarItem(
          icon: Image.asset(item['icon'],width: 30,height: 30,),
          activeIcon: Image.asset(item['activeIcon'],width: 30,height: 30,),
          label: item['label']
        )
      );
    }
    return list;
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    tokenmanager.init();
    // 订阅消息
    registerLogoutEvent();    
  } 
  registerLogoutEvent(){
    eventBus.on<LogoutEvent>().listen((event) {
      // 跳转到登录页面
      Navigator.pushNamed(context,'/login');
    });
  }


  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      // 安全区组件
      // body: SafeArea(
      //   child: getTabbarContent(),
      // ),
      body: SafeArea(
        child: IndexedStack(
          index: _currentIndex,
          children:  [
            const HomePage(),
            MinePage(currentIndex:_currentIndex,updateIndex: updateIndex)],
        )
      ),  
      bottomNavigationBar: BottomNavigationBar(
        selectedItemColor: const Color.fromRGBO(85, 145, 175,1),
        unselectedItemColor: Colors.black,
        items: getBottomNavigationBarItems(),
        type: BottomNavigationBarType.fixed,
        currentIndex: _currentIndex,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        }
      ),
    );
  }
}
